#include "util/PgmImage.h"
#include <stdexcept>

namespace util {

Image PgmImage::fromStream(std::istream& is) const
{
  std::string header;
  is >> header;
  if (header != "P5")
    throw std::logic_error("Not a PGM file.");

  int width, height;
  is >> width >> height;
  Image img(width, height);

  int max;
  is >> max;
  is.get(); // eat std::endl
  for (std::size_t y = 0; y < img.getHeight() && is.good(); ++y)
  {
    for (std::size_t x = 0; x < img.getWidth() && is.good(); ++x)
    {
      img.setValue(x, y, is.get());
    }
  }
  return img;
}

void PgmImage::toStream(std::ostream& os, const Image& img)
{
  os << "P5" << std::endl;
  os << img.getWidth() << " " << img.getHeight() << std::endl;
  os << "255" << std::endl;
  for (std::size_t y = 0; y < img.getHeight() && os.good(); ++y)
  {
    for (std::size_t x = 0; x < img.getWidth() && os.good(); ++x)
    {
      os << (char)img.getValue(x, y);
    }
  }
}

} // namespace util
